package com.security.user.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.security.user.mapper.AuditLogMapper;
import com.security.user.model.AuditLog;
import com.security.user.model.UserInfo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author yanggld
 * @Date 2020/3/9-14:39
 */
@Component
public class AuditLogInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AuditLogMapper auditLogMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        System.out.println("**********审计日志");

        AuditLog auditLog = new AuditLog();
        auditLog.setMethod(request.getMethod());
        auditLog.setPath(request.getRequestURI());
        UserInfo userInfo = (UserInfo)request.getAttribute("user");
        if (userInfo != null) {
            auditLog.setUsername(userInfo.getUsername());
        }
        auditLogMapper.save(auditLog);
        request.setAttribute("auditLogId",auditLog.getId());
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        Long auditLogId = (Long)request.getAttribute("auditLogId");
        AuditLog auditLog = auditLogMapper.getById(auditLogId);
        auditLog.setStatus(response.getStatus());
        auditLogMapper.update(auditLog);
        System.out.println("***审计日志***"+ JSONObject.toJSONString(auditLog));
        super.afterCompletion(request, response, handler, ex);
    }
}
